package com.mhl.campuscabinet;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.mhl.adapter.ProductAdapter;
import com.mhl.client.OkHttpUtils;
import com.mhl.entity.LocalData;
import com.mhl.entity.Product;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ResultActivity extends AppCompatActivity {

    // keyword是从搜索框界面通过Intent传过来的，需要客户端完成一下
    private String keyword;
    private List<Product> productList = new ArrayList<>();
    private ProductAdapter adapter;
    private String result;
    //private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        loadResultProduct();
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycle_view);
        StaggeredGridLayoutManager layoutManager = new
                StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        // 解决重新分配高度的问题
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull @NotNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                layoutManager.invalidateSpanAssignments(); //防止第一行到顶部有空白区域
            }
        });
        adapter = new ProductAdapter(productList, this);
        recyclerView.setAdapter(adapter);

    }

    // 加载搜索结果
    private void loadResultProduct() {

        Intent intent = getIntent();
        result = intent.getStringExtra("result");
        System.out.println("传过来的字符为！！！！！！！！" + result);

        JSONObject req = new JSONObject();
        MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
        try {
            req.put("name", result);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String json = req.toString();
        RequestBody requestBody = RequestBody.Companion.create(json, mediaType);

        OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp2() + "merchandise/search", requestBody, new Callback() {

            //Handler h = handler;

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                System.out.println(e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                final String ItemsString = response.body().string();
                try {
                    int state = 1;
                    try {
                        JSONObject errcodeJson = new JSONObject(ItemsString);
                        state = errcodeJson.getInt("errcode");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    Looper.prepare();
                    if (state == 1) {
                        Toast.makeText(ResultActivity.this, "input problem", Toast.LENGTH_SHORT).show();
                    } else if (state == 2) {
                        Toast.makeText(ResultActivity.this, "server error", Toast.LENGTH_SHORT).show();
                    } else {
                        JSONObject data = new JSONObject(ItemsString);
                        JSONArray itemArray = data.getJSONArray("data");
                        for (int i = 0; i < itemArray.length(); i++) {
                            JSONObject item = itemArray.getJSONObject(i);
                            Product product = new Product();
                            product.setPrice(item.getDouble("pre_price"));
                            //product.setDescription(item.getString("description"));
                            product.setName(item.getString("name"));
                            JSONArray urls = item.getJSONArray("url_list");
                            product.setURL(urls.getString(0));
                            product.setId(item.getInt("id"));
                            productList.add(product);
                            //test
                            System.out.println("loaded product:");
                            System.out.println("name:   " + product.getName());
                            System.out.println("url!!!!!");
                            System.out.println("url:   " + product.getURL());
                            //h.sendEmptyMessage(type);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
//                                        System.out.println("开始显示商品");
                                    adapter.notifyDataSetChanged();
                                }
                            });
                        }

                    }
                    Looper.loop();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            //System.out.println(result);
        });
    }
}